const defaultConfig = {
  id: 'id',
  pid: 'pid',
  children: 'children',
};

const getConfig = (config) => {
  return Object.assign({}, defaultConfig, config);
};

export function listConvertToTree(data: any[], callback?, config?) {
  const { id, pid, children } = getConfig(config);
  const nodeMap = new Map();
  let result: any = [];

  for (const node of data) {
    node[children] = node[children] || [];
    nodeMap.set(node[id], node);
  }

  for (const node of data) {
    let parent = nodeMap.get(node[pid]);
    if (parent) {
      parent[children].push(node);
      callback && callback(parent, children);
    } else {
      result.push(node);
    }
  }
  return result;
}
